// ==UserScript==
// @name         快麦ERP辅助
// @namespace    http://tampermonkey.net/
// @version      1.9.4
// @description  手动根据采购价计算并修正售价，带日志显示面板和自定义滚动时间，支持自动翻页。
// @author       Your Name
// @match        https://erpb.superboss.cc/*
// @grant        GM_addStyle
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_log
// ==/UserScript==

(function() {
    'use strict';

    // 调试模式
    const DEBUG = true;
    const MAX_LOG_ENTRIES = 50;
    let logEntries = [];

    function log(message) {
        const timestamp = new Date().toLocaleTimeString();
        const logMessage = `[${timestamp}] ${message}`;

        if (DEBUG) {
            console.log('[ERP Price Tool]', message);
            GM_log(logMessage);
        }

        logEntries.push(logMessage);
        if (logEntries.length > MAX_LOG_ENTRIES) {
            logEntries.shift();
        }

        updateLogDisplay();
    }

    // 默认参数
    const defaultParams = {
        lowPriceMultiplier: 2,
        lowPriceAddition: 2,
        midPriceMultiplier: 2,
        midPriceAddition: 0,
        highPriceMultiplier: 1,
        highPriceAddition: 15,
        lowPriceThreshold: 10,
        highPriceThreshold: 20,
        clickDelay: 500,
        inputDelay: 500,
        itemDelay: 500,
        scrollDuration: 10,
        pageDelay: 2000,
        postPageDelay: 3000 // 新增页面跳转后的延迟
    };

    // 全局变量
    let formulaParams = GM_getValue('formulaParams', defaultParams);
    let isRunning = false;
    let processTimeout = null;
    let currentIndex = 0;
    let adjustedCount = 0;
    let purchasePriceCells = [];
    let panelObserver = null;
    let scrollObserver = null;
    let isPanelMinimized = false;
    let isLastPage = false;

    // 计算销售价的函数
    function calculateSellingPrice(purchasePrice) {
        if (purchasePrice < formulaParams.lowPriceThreshold) {
            return purchasePrice * formulaParams.lowPriceMultiplier + formulaParams.lowPriceAddition;
        } else if (purchasePrice <= formulaParams.highPriceThreshold) {
            return purchasePrice * formulaParams.midPriceMultiplier + formulaParams.midPriceAddition;
        } else {
            return purchasePrice * formulaParams.highPriceMultiplier + formulaParams.highPriceAddition;
        }
    }

    // 更新日志显示
    function updateLogDisplay() {
        const logDisplay = document.getElementById('erp-log-display');
        if (logDisplay) {
            logDisplay.innerHTML = logEntries.join('<br>');
            logDisplay.scrollTop = logDisplay.scrollHeight;
        }
    }

    // 停止处理函数
    function stopProcessing() {
        isRunning = false;
        isLastPage = false;
        if (processTimeout) {
            clearTimeout(processTimeout);
            processTimeout = null;
        }
        if (scrollObserver) {
            scrollObserver.disconnect();
            scrollObserver = null;
            log('滚动观察器已停止');
        }

        const runBtn = document.getElementById('erp-run-btn');
        if (runBtn) {
            runBtn.textContent = '立即执行';
            runBtn.classList.remove('stop');
        }
        updateStatus('已停止');
        log('处理已停止');
    }

    // 更新状态函数
    function updateStatus(message) {
        const statusElement = document.getElementById('erp-status');
        if (statusElement) {
            statusElement.textContent = message;
        }
    }

    // 保存设置并执行函数
    function saveSettingsAndRun() {
        formulaParams = {
            lowPriceMultiplier: parseFloat(document.getElementById('erp-low-multiplier').value),
            lowPriceAddition: parseFloat(document.getElementById('erp-low-addition').value),
            midPriceMultiplier: parseFloat(document.getElementById('erp-mid-multiplier').value),
            midPriceAddition: parseFloat(document.getElementById('erp-mid-addition').value),
            highPriceMultiplier: parseFloat(document.getElementById('erp-high-multiplier').value),
            highPriceAddition: parseFloat(document.getElementById('erp-high-addition').value),
            lowPriceThreshold: parseFloat(document.getElementById('erp-low-threshold').value),
            highPriceThreshold: parseFloat(document.getElementById('erp-high-threshold').value),
            clickDelay: parseInt(document.getElementById('erp-click-delay').value),
            inputDelay: parseInt(document.getElementById('erp-input-delay').value),
            itemDelay: parseInt(document.getElementById('erp-item-delay').value),
            scrollDuration: parseInt(document.getElementById('erp-scroll-duration').value),
            pageDelay: parseInt(document.getElementById('erp-page-delay').value) || 2000,
            postPageDelay: parseInt(document.getElementById('erp-post-page-delay').value) || 3000
        };
        GM_setValue('formulaParams', formulaParams);
        log('设置已保存: ' + JSON.stringify(formulaParams));

        // ✨ 新增或修改这三行，确保每次启动都重置 ✨
        currentIndex = 0; // 重置当前处理的商品索引
        adjustedCount = 0; // 重置已修正商品数量
        purchasePriceCells = []; // 清空商品列表，以便重新获取当前页数据


        isRunning = true;
        isLastPage = false;
        const runBtn = document.getElementById('erp-run-btn');
        runBtn.textContent = '停止执行';
        runBtn.classList.add('stop');
        updateStatus('正在执行...');

        adjustSellingPrices();
    }

    // 自动滚动函数
    function startAutoScroll() {
        if (scrollObserver) {
            scrollObserver.disconnect();
        }

        const container = document.querySelector('.ui-datalist-bd');
        if (!container) {
            log('未找到滚动容器');
            return;
        }

        container.scrollTop = container.scrollHeight;
        log('初始滚动到底部');

        scrollObserver = new MutationObserver(function() {
            container.scrollTop = container.scrollHeight;
        });

        scrollObserver.observe(container, {
            childList: true,
            subtree: true,
            characterData: true
        });

        log(`已启动滚动观察器，将持续 ${formulaParams.scrollDuration} 秒`);

        setTimeout(() => {
            if (scrollObserver) {
                scrollObserver.disconnect();
                scrollObserver = null;
                log('自动滚动已停止');
            }
        }, formulaParams.scrollDuration * 1000);
    }

    // 检查是否最后一页
    function checkIsLastPage() {
        const pageInfo = document.querySelector('.rc-pages_btns');
        if (!pageInfo) {
            log('未找到分页信息');
            return false;
        }

        const currentPageSpan = pageInfo.querySelector('.crt');
        const totalPageText = Array.from(pageInfo.querySelectorAll('span'))
        .find(span => span.textContent.includes('共'));

        if (!currentPageSpan || !totalPageText) {
            log('未找到当前页码或总页数');
            return false;
        }

        const currentPage = parseInt(currentPageSpan.textContent);
        const totalPage = parseInt(totalPageText.textContent.replace('共', '').replace('页', ''));

        if (isNaN(currentPage) || isNaN(totalPage)) {
            log('页码解析失败');
            return false;
        }

        return currentPage >= totalPage;
    }

    // 跳转到下一页
    function goToNextPage() {
        const nextPageBtn = document.querySelector('.rc-pages_btn-next');
        if (!nextPageBtn) {
            log('未找到下一页按钮');
            isLastPage = true;
            return false;
        }

        if (checkIsLastPage()) {
            log('已经是最后一页');
            isLastPage = true;
            return false;
        }

        log('准备跳转到下一页');
        nextPageBtn.click();
        return true;
    }

    // 处理下一个行
    function processNextItem() {
        if (!isRunning) {
            log('处理被用户停止');
            return;
        }

        if (currentIndex >= purchasePriceCells.length) {
            log(`当前页完成: 共修正 ${adjustedCount} 个售价`);

            // 检查是否最后一页
            if (checkIsLastPage()) {
                log('所有页面处理完成');
                stopProcessing();
                updateStatus('执行完成');
                return;
            }

            // 跳转到下一页
            if (goToNextPage()) {
                log(`等待 ${formulaParams.postPageDelay} 毫秒后处理新页面`);
                processTimeout = setTimeout(() => {
                    // 重置索引和单元格引用
                    currentIndex = 0;
                    purchasePriceCells = [];
                    adjustedCount = 0;

                    // 重新开始处理
                    adjustSellingPrices();
                }, formulaParams.postPageDelay);
            } else {
                log('无法跳转到下一页');
                stopProcessing();
                updateStatus('执行完成');
            }
            return;
        }

        const purchaseCell = purchasePriceCells[currentIndex];
        currentIndex++;

        const purchasePrice = parseFloat(purchaseCell.getAttribute('data-title'));
        if (isNaN(purchasePrice)) {
            log(`单元格 ${currentIndex} 的采购价不是有效数字`);
            processTimeout = setTimeout(processNextItem, formulaParams.itemDelay);
            return;
        }

        const correctSellingPrice = calculateSellingPrice(purchasePrice);
        const row = purchaseCell.closest('.ui-datalist-item');
        const sellingCell = row.querySelector('.ui-datalist_cell-sellingPrice');

        if (sellingCell) {
            const currentSellingPrice = parseFloat(sellingCell.getAttribute('data-title'));

            if (currentSellingPrice !== correctSellingPrice) {
                log(`发现不匹配的售价: 成本价=${purchasePrice}, 当前售价=${currentSellingPrice}, 应修正为=${correctSellingPrice}`);

                processTimeout = setTimeout(() => {
                    sellingCell.click();
                    log(`已点击第 ${currentIndex} 个售价单元格`);

                    processTimeout = setTimeout(() => {
                        const input = sellingCell.querySelector('input[name="sellingPrice"]');
                        if (input) {
                            input.value = correctSellingPrice;
                            const event = new Event('change', { bubbles: true });
                            input.dispatchEvent(event);
                            adjustedCount++;
                            log(`已修正第 ${currentIndex} 个售价`);
                        } else {
                            log(`无法找到第 ${currentIndex} 个售价的输入框`);
                        }

                        processTimeout = setTimeout(processNextItem, formulaParams.itemDelay);
                    }, formulaParams.inputDelay);
                }, formulaParams.clickDelay);
            } else {
                processTimeout = setTimeout(processNextItem, formulaParams.itemDelay);
            }
        } else {
            log(`无法找到第 ${currentIndex} 个采购价对应的售价单元格`);
            processTimeout = setTimeout(processNextItem, formulaParams.itemDelay);
        }
    }

    // 调整售价的主函数
    function adjustSellingPrices() {
        log('开始处理新页面...');

        // 先启动自动滚动
        startAutoScroll();
        log(`当前延迟设置: 点击延迟=${formulaParams.clickDelay}ms, 输入延迟=${formulaParams.inputDelay}ms, 项目间隔=${formulaParams.itemDelay}ms, 页面延迟=${formulaParams.pageDelay}ms, 跳转后延迟=${formulaParams.postPageDelay}ms`);

        const checkInterval = setInterval(() => {
            const newCells = document.querySelectorAll('.ui-datalist_cell-purchasePrice');
            if (newCells.length > 0) {
                purchasePriceCells = newCells;
                log(`找到 ${purchasePriceCells.length} 个采购价单元格`);

                clearInterval(checkInterval);
                setTimeout(() => {
                    processNextItem();
                }, 1000);
            }
        }, 500);

        setTimeout(() => {
            clearInterval(checkInterval);
            if (purchasePriceCells.length === 0) {
                purchasePriceCells = document.querySelectorAll('.ui-datalist_cell-purchasePrice');
                log(`最终找到 ${purchasePriceCells.length} 个采购价单元格`);
                setTimeout(() => {
                    processNextItem();
                }, 1000);
            }
        }, formulaParams.scrollDuration * 1000);
    }

    // 切换面板状态
    function togglePanel() {
        const panel = document.getElementById('erp-price-control-panel');
        const minimizedBtn = document.getElementById('erp-minimized-btn');

        if (isPanelMinimized) {
            // 展开面板
            panel.style.display = 'flex';
            minimizedBtn.style.display = 'none';
            isPanelMinimized = false;
            log('面板已展开');
        } else {
            // 最小化面板
            panel.style.display = 'none';
            minimizedBtn.style.display = 'block';
            isPanelMinimized = true;
            log('面板已最小化');
        }
    }

    // 创建控制面板
    function createControlPanel() {
        log('尝试创建控制面板...');

        const existingPanel = document.getElementById('erp-price-control-panel');
        if (existingPanel) {
            existingPanel.remove();
            log('已移除现有的控制面板');
        }

        const panel = document.createElement('div');
        panel.id = 'erp-price-control-panel';

        // 更新样式
        GM_addStyle(`
            #erp-price-control-panel {
                position: fixed;
                top: 40px;
                right: 20px;
                width: 380px;
                background: #f5f5f5;
                border: 1px solid #ddd;
                border-radius: 5px;
                padding: 15px;
                box-shadow: 0 2px 10px rgba(0,0,0,0.1);
                z-index: 99999;
                font-family: Arial, sans-serif;
                max-height: 80vh;
                display: flex;
                flex-direction: column;
            }
            #erp-minimized-btn {
                position: fixed;
                top: 40px;
                right: 20px;
                width: 40px;
                height: 40px;
                background: #E8785F;
                color: white;
                border-radius: 50%;
                display: none;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                box-shadow: 0 2px 5px rgba(0,0,0,0.2);
                z-index: 99999;
                font-weight: bold;
                font-size: 16px;
                line-height: 40px;
                text-align: center;
                padding: 0;
            }
            #erp-minimized-btn:hover {
                background: #d76b53;
            }
            .erp-control-group {
                margin-bottom: 10px;
            }
            .erp-control-group label {
                display: block;
                margin-bottom: 5px;
                font-weight: bold;
            }
            .erp-control-group input {
                width: 100%;
                padding: 5px;
                border: 1px solid #ccc;
                border-radius: 3px;
            }
            #erp-run-btn {
                width: 100%;
                padding: 8px;
                margin-top: 5px;
                background-color: #4CAF50;
                color: white;
                border: none;
                border-radius: 3px;
                cursor: pointer;
            }
            #erp-run-btn:hover {
                background-color: #45a049;
            }
            #erp-run-btn.stop {
                background-color: #f44336;
            }
            #erp-run-btn.stop:hover {
                background-color: #d32f2f;
            }
            #erp-status {
                font-weight: bold;
                color: #333;
            }
            .delay-controls {
                background: #f0f0f0;
                padding: 10px;
                border-radius: 3px;
                margin-top: 10px;
            }
            #erp-log-display {
                flex: 1;
                margin-top: 10px;
                padding: 10px;
                background: #fff;
                border: 1px solid #ddd;
                border-radius: 3px;
                overflow-y: auto;
                font-size: 12px;
                line-height: 1.4;
                max-height: 200px;
                min-height: 100px;
            }
            .log-clear-btn {
                margin-top: 5px;
                padding: 5px;
                background: #e0e0e0;
                border: none;
                border-radius: 3px;
                cursor: pointer;
            }
            .log-clear-btn:hover {
                background: #d0d0d0;
            }
            .panel-header {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 10px;
            }
            .panel-title {
                margin: 0;
                color: #E8785F;
            }
            .minimize-btn {
                background: none;
                border: none;
                font-size: 16px;
                cursor: pointer;
                color: #999;
            }
            .minimize-btn:hover {
                color: #666;
            }
            .inline-control-group {
                display: flex;
                align-items: center;
                gap: 10px;
            }
            .inline-control-group input {
                width: 60px !important;
            }
            .price-range-group {
                display: flex;
                margin-bottom: 2px;
                align-items: center;
                justify-content: space-between
            }
            .price-range-group label {
                min-width: 2px;
                margin: 2px;
            }
            .price-range-group input {
                width: 60px;
                margin: 2px;
                text-align: center;
            }
        `);

        panel.innerHTML = `
            <div class="panel-header">
                <h1 class="panel-title">售价修正工具 v1.9.4</h1>
                <button class="minimize-btn" id="erp-minimize-btn" title="最小化">−</button>
            </div>

            <div class="price-range-group">
                <div>
                    <label style="font-weight: bold; color: #4A93F3;">低价阈值：</label>
                    <input type="number" id="erp-low-threshold" step="0.1" value="${formulaParams.lowPriceThreshold}">
                    <label>元</label>
                </div>
                <div>
                    <label style="font-weight: bold; color: #4A93F3;">高价阈值：</label>
                    <input type="number" id="erp-high-threshold" step="0.1" value="${formulaParams.highPriceThreshold}">
                    <label>元</label>
                </div>
            </div>

            <div class="price-range-group">
                <div>
                    <label style="font-weight: bold; color: #4A93F3;">成本价 &lt; ${formulaParams.lowPriceThreshold}</label>
                </div>
                <div>
                    <label>售价 = 成本价 * </label>
                    <input type="number" id="erp-low-multiplier" step="0.1" value="${formulaParams.lowPriceMultiplier}">
                    <label>+</label>
                    <input type="number" id="erp-low-addition" step="0.1" value="${formulaParams.lowPriceAddition}">
                </div>
            </div>

            <div class="price-range-group">
                <div>
                    <label style="font-weight: bold; color: #4A93F3;">${formulaParams.lowPriceThreshold} ≤ 成本价 ≤ ${formulaParams.highPriceThreshold}</label>
                </div>
                <div>
                    <label>售价 = 成本价 * </label>
                    <input type="number" id="erp-mid-multiplier" step="0.1" value="${formulaParams.midPriceMultiplier}">
                    <label>+</label>
                    <input type="number" id="erp-mid-addition" step="0.1" value="${formulaParams.midPriceAddition}">
                </div>
            </div>

            <div class="price-range-group">
                <div>
                    <label style="font-weight: bold; color: #4A93F3;">成本价 &gt; ${formulaParams.highPriceThreshold}</label>
                </div>
                <div>
                    <label>售价 = 成本价 * </label>
                    <input type="number" id="erp-high-multiplier" step="0.1" value="${formulaParams.highPriceMultiplier}">
                    <label>+</label>
                    <input type="number" id="erp-high-addition" step="0.1" value="${formulaParams.highPriceAddition}">
                </div>
            </div>

            <div class="delay-controls">
                <div class="erp-control-group inline-control-group">
                    <label for="erp-scroll-duration">滚动持续时间:</label>
                    <input type="number" id="erp-scroll-duration" min="1" step="1" value="${formulaParams.scrollDuration}">
                    <label for="erp-input-delay">s</label>
                </div>
                <div class="erp-control-group inline-control-group">
                    <label for="erp-item-delay">项目间隔:</label>
                    <input type="number" id="erp-item-delay" min="100" step="100" value="${formulaParams.itemDelay}">
                    <label for="erp-input-delay">ms</label>
                </div>
                <div class="erp-control-group inline-control-group">
                    <label for="erp-click-delay">点击延迟:</label>
                    <input type="number" id="erp-click-delay" min="100" step="100" value="${formulaParams.clickDelay}">
                    <label for="erp-input-delay">ms</label>
                </div>
                <div class="erp-control-group inline-control-group">
                    <label for="erp-input-delay">输入延迟:</label>
                    <input type="number" id="erp-input-delay" min="100" step="100" value="${formulaParams.inputDelay}">
                    <label for="erp-input-delay">ms</label>
                </div>
                <div class="erp-control-group inline-control-group">
                    <label for="erp-page-delay">页面跳转延迟:</label>
                    <input type="number" id="erp-page-delay" min="500" step="100" value="${formulaParams.pageDelay}">
                    <label for="erp-page-delay">ms</label>
                </div>
                <div class="erp-control-group inline-control-group">
                    <label for="erp-post-page-delay">跳转后延迟:</label>
                    <input type="number" id="erp-post-page-delay" min="1000" step="500" value="${formulaParams.postPageDelay}">
                    <label for="erp-post-page-delay">ms</label>
                </div>
            </div>
            <button id="erp-run-btn">立即执行</button>
            <div style="margin-top:10px;font-size:12px;color:#666;">
                状态: <span id="erp-status">就绪</span>
            </div>
            <div style="margin-top:10px;">
                <div>操作日志:</div>
                <div id="erp-log-display"></div>
                <button class="log-clear-btn" id="erp-log-clear">清空日志</button>
            </div>
        `;

        // 创建最小化按钮
        const minimizedBtn = document.createElement('div');
        minimizedBtn.id = 'erp-minimized-btn';
        minimizedBtn.textContent = '辅助';
        minimizedBtn.style.display = 'none';
        minimizedBtn.addEventListener('click', togglePanel);

        document.body.appendChild(panel);
        document.body.appendChild(minimizedBtn);
        log('控制面板已创建');

        // 执行/停止按钮事件
        document.getElementById('erp-run-btn').addEventListener('click', function() {
            if (isRunning) {
                stopProcessing();
            } else {
                saveSettingsAndRun();
            }
        });

        // 清空日志按钮事件
        document.getElementById('erp-log-clear').addEventListener('click', function() {
            logEntries = [];
            updateLogDisplay();
            log('日志已清空');
        });

        // 最小化按钮事件
        document.getElementById('erp-minimize-btn').addEventListener('click', togglePanel);
    }

    // 初始化函数
    function init() {
        log('脚本初始化开始');

        if (!document.body) {
            setTimeout(init, 100);
            return;
        }

        panelObserver = new MutationObserver(function(mutations) {
            const panel = document.getElementById('erp-price-control-panel');
            if (!panel) {
                log('检测到控制面板不存在，重新创建');
                createControlPanel();
            }
        });

        panelObserver.observe(document.body, {
            childList: true,
            subtree: false,
            attributes: false
        });

        createControlPanel();
    }

    // 页面加载后初始化
    if (document.readyState === 'complete') {
        init();
    } else {
        window.addEventListener('load', init);
    }

    // 暴露停止函数到全局
    window.stopERPPriceAdjustment = stopProcessing;
})();